<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Overtrue\EasySms\EasySms;
use \Cache;
use Illuminate\Support\Arr;

class SMSController extends Controller
{
    /**
     * 发送云片消息
     * @param $type
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     * @throws \Overtrue\EasySms\Exceptions\InvalidArgumentException
     * @throws \Overtrue\EasySms\Exceptions\NoGatewayAvailableException
     */
    public function send($type, Request $request)
    {
        $request->validate(['phone' => 'required']);
        $easySms = $this->initSMSClient();
        switch ($type) {
            case 'yunpian':
                $this->validate($request, [
                    'content' => 'required'
                ]);
                $result = $easySms->send($request->input('phone'), ['content' => $request->input('content')], ['yunpian']);
                break;
            case 'aliyun':
                $this->validate($request, [
                    'template' => 'required',
                    'data' => 'required',
                ]);
                $result = $easySms->send($request->input('phone'), [
                    'template' => $request->input('template'),
                    'data' => $request->input('date'), //array
                ], ['aliyun']);
                break;
            default:
                $result = $easySms->send($request->input('phone'), [
                    'content' => 'required',
                    'template' => $request->input('template'),
                    'data' => $request->input('date')
                ]);

        }

        return response()->json($result);
    }


    /**
     * 用云片发送登录验证Code，验证码3分钟过期
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Overtrue\EasySms\Exceptions\InvalidArgumentException
     * @throws \Overtrue\EasySms\Exceptions\NoGatewayAvailableException
     */
    public function loginCode(Request $request)
    {

        $request->validate(['phone' => 'required']);
        $easySms = $this->initSMSClient();
//        $content = '您的短信验证码是%s，5分钟后失效';
        $content = '客观、您的验证码是%s、如果不是本人操作、请忽略、';
        $code = rand(1000, 9999);

        Cache::put('login_' . $request->phone, $code, 3600); // 3分钟Code过期.

        $content = sprintf($content, $code);


        try {
            $result = $easySms->send($request->phone, ['content' => $content], ['yunpian']);
        } catch (\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $exception) {
            $message = $exception->getResults();
        }
        if (Arr::get($result, 'yunpian.status') === 'success') {

            return response()->json($result, 200);
        }

        return response()->json($result, 400);
    }

    /**
     * 初始化EasySMS实例
     * @return EasySms
     */
    protected function initSMSClient()
    {
        $config = [
            // HTTP 请求的超时时间（秒）
            'timeout' => 3.0,
            // 默认发送配置
            'default' => [
                // 网关调用策略，默认：顺序调用
                'strategy' => \Overtrue\EasySms\Strategies\OrderStrategy::class,

                // 默认可用的发送网关
                'gateways' => [
                    'yunpian'
                ],
            ],
            // 可用的网关配置
            'gateways' => [
                'errorlog' => [
                    'file' => storage_path('logs/easy-sms.log'),
                ],
                'yunpian' => [
                    'api_key' => env('YUNPIAN_APPKEY'),
                ],
            ],
        ];

        return new EasySms($config);
    }
}
